package com.example.controller;

import com.example.model.Pricing;
import com.example.repository.PricingRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/pricing")
@Tag(name = "价格管理", description = "价格配置的创建、查询、更新和管理")
public class PricingController {
    
    @Autowired
    private PricingRepository pricingRepository;

    @PostMapping
    @Operation(summary = "创建价格配置")
    public ResponseEntity<Pricing> createPricing(@Valid @RequestBody Pricing pricing) {
        Pricing createdPricing = pricingRepository.save(pricing);
        return ResponseEntity.ok(createdPricing);
    }

    @GetMapping
    @Operation(summary = "获取价格配置列表")
    public ResponseEntity<Page<Pricing>> getAllPricing(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "itemType") String sortBy,
            @RequestParam(defaultValue = "asc") String sortDir,
            @RequestParam(required = false) String pricingType,
            @RequestParam(required = false) Boolean activeOnly) {
        
        Sort sort = Sort.by(Sort.Direction.fromString(sortDir), sortBy);
        Pageable pageable = PageRequest.of(page, size, sort);
        
        if (Boolean.TRUE.equals(activeOnly)) {
            return ResponseEntity.ok(pricingRepository.findByIsActiveTrue(pageable));
        }
        
        return ResponseEntity.ok(pricingRepository.findAll(pageable));
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取价格配置详情")
    public ResponseEntity<Pricing> getPricingDetail(@PathVariable Long id) {
        return pricingRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新价格配置")
    public ResponseEntity<Pricing> updatePricing(
            @PathVariable Long id,
            @Valid @RequestBody Pricing pricing) {
        return pricingRepository.findById(id)
                .map(existingPricing -> {
                    pricing.setId(id);
                    Pricing updatedPricing = pricingRepository.save(pricing);
                    return ResponseEntity.ok(updatedPricing);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除价格配置")
    public ResponseEntity<Void> deletePricing(@PathVariable Long id) {
        if (pricingRepository.existsById(id)) {
            pricingRepository.deleteById(id);
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/search")
    @Operation(summary = "搜索价格配置")
    public ResponseEntity<List<Pricing>> searchPricing(@RequestParam String itemType) {
        List<Pricing> pricingList = pricingRepository.findByItemTypeContainingAndIsActiveTrue(itemType);
        return ResponseEntity.ok(pricingList);
    }

    @GetMapping("/discounts")
    @Operation(summary = "获取有折扣的价格配置")
    public ResponseEntity<List<Pricing>> getDiscountPricing() {
        List<Pricing> discountPricing = pricingRepository.findActiveDiscountPricing();
        return ResponseEntity.ok(discountPricing);
    }

    @GetMapping("/type/{type}")
    @Operation(summary = "根据价格类型获取配置")
    public ResponseEntity<List<Pricing>> getPricingByType(@PathVariable String type) {
        try {
            Pricing.PricingType pricingType = Pricing.PricingType.valueOf(type.toUpperCase());
            List<Pricing> pricingList = pricingRepository.findByPricingTypeAndIsActiveTrue(pricingType);
            return ResponseEntity.ok(pricingList);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取价格统计")
    public ResponseEntity<Map<String, Object>> getPricingStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 各价格类型统计
        List<Object[]> typeStats = pricingRepository.countByPricingType();
        statistics.put("pricingTypeStatistics", typeStats);
        
        // 总价格配置数
        long totalPricing = pricingRepository.count();
        statistics.put("totalPricing", totalPricing);
        
        // 活跃价格配置数
        long activePricing = pricingRepository.findByIsActiveTrue(PageRequest.of(0, Integer.MAX_VALUE)).getTotalElements();
        statistics.put("activePricing", activePricing);
        
        // 有折扣的价格配置数
        List<Pricing> discountPricing = pricingRepository.findActiveDiscountPricing();
        statistics.put("discountPricing", discountPricing.size());
        
        return ResponseEntity.ok(statistics);
    }

    @PutMapping("/{id}/toggle-status")
    @Operation(summary = "切换价格配置状态")
    public ResponseEntity<Pricing> togglePricingStatus(@PathVariable Long id) {
        return pricingRepository.findById(id)
                .map(pricing -> {
                    pricing.setIsActive(!pricing.getIsActive());
                    Pricing updatedPricing = pricingRepository.save(pricing);
                    return ResponseEntity.ok(updatedPricing);
                })
                .orElse(ResponseEntity.notFound().build());
    }
}
